package com.mycjj.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mycjj.android.R;
import com.mycjj.android.activity.AboutCjjActivity;
import com.mycjj.android.activity.My_CarListActivity;
import com.mycjj.android.activity.QiuZhuActivity;
import com.mycjj.android.activity.SettingInfoActivity;
import com.mycjj.android.activity.SuggestActivity;
import com.mycjj.android.activity.TiXingActivity;
import com.mycjj.android.activity.WeiZhangActivity;
import com.mycjj.android.activity.YuyueActivity;
import com.mycjj.android.bean.ArticlecClassBaseBean;
import com.mycjj.android.bean.ArticlecClassBaseBean.ArticleType;
import com.mycjj.android.bean.CarInfoBaseBean.CarInfo;
import com.mycjj.android.bean.WeatherBaseBean;
import com.mycjj.android.bean.WeatherBaseBean.Weather;
import com.mycjj.android.http.ProjectHttpRequestImpl;
import com.mycjj.android.http.ProjectHttpRequestInterface;
import com.mycjj.android.util.Preferences;
import com.mycjj.android.util.Utils;
import com.mycjj.android.widget.TabPageIndicator;

import de.greenrobot.event.EventBus;

public class MyFragment extends BaseFragment implements android.view.View.OnClickListener, android.view.View.OnTouchListener {

	private ImageView mHeaderLeftButton;
	private ImageView mHeaderRightButton;
	private TextView mHeaderTitleTextView;

	private RelativeLayout rl_pop_menu0, rl_pop_menu1, rl_pop_menu2,rl_pop_menu3;

	private View rootView;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (rootView == null) {
			rootView = (View) inflater.inflate(R.layout.fragment_my, null);
			rootView.setOnTouchListener(this);
			mPopView = inflater.inflate(R.layout.pop_main_view, null);
		}
		// 缓存的rootView需要判断是否已经被加过parent，
		// 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		init(rootView);
		return rootView;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		EventBus.getDefault().register(this);
	}

	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

	}

	private ViewPager pager;
	private TabPageIndicator indicator;

	private ImageView iv_car_logo;
	private ImageView iv_yy, iv_wz, iv_tx, iv_qz;
	private TextView tv_car_nums;
	private TextView tv_weather_msg;
	private TextView tv_notification_msg;

	private TextView tv_reservation_count, tv_violate_regulations_count, tv_notification_count, tv_helper_count;

	private void init(View view) {

		mHeaderLeftButton = (ImageView) view.findViewById(R.id.header_left_button);
		mHeaderLeftButton.setVisibility(View.VISIBLE);
		mHeaderLeftButton.setBackgroundResource(R.drawable.iv_white_icon);
		mHeaderRightButton = (ImageView) view.findViewById(R.id.header_right_button);
		mHeaderRightButton.setVisibility(View.VISIBLE);
		mHeaderRightButton.setBackgroundResource(R.drawable.iv_right_bg);
		mHeaderTitleTextView = (TextView) view.findViewById(R.id.header_title_textview);
		mHeaderTitleTextView.setText("加入车加佳，生活更精彩");
		mHeaderTitleTextView.setTextSize(16.0f);
		mHeaderRightButton.setOnClickListener(this);
		iv_car_logo = (ImageView) view.findViewById(R.id.iv_car_logo);
		tv_car_nums = (TextView) view.findViewById(R.id.tv_car_nums);

		tv_weather_msg = (TextView) view.findViewById(R.id.tv_weather_msg);

		tv_notification_msg = (TextView) view.findViewById(R.id.tv_notification_msg);

		tv_reservation_count = (TextView) view.findViewById(R.id.tv_reservation_count);
		tv_violate_regulations_count = (TextView) view.findViewById(R.id.tv_violate_regulations_count);
		tv_notification_count = (TextView) view.findViewById(R.id.tv_notification_count);
		tv_helper_count = (TextView) view.findViewById(R.id.tv_helper_count);

		tv_reservation_count.setVisibility(View.GONE);
		tv_violate_regulations_count.setVisibility(View.GONE);
		tv_notification_count.setVisibility(View.GONE);
		tv_helper_count.setVisibility(View.GONE);
		pager = (ViewPager) view.findViewById(R.id.pager);
		indicator = (TabPageIndicator) view.findViewById(R.id.indicator);

		iv_yy = (ImageView) view.findViewById(R.id.iv_reservation);
		iv_yy.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getActivity(), YuyueActivity.class));
			}
		});

		iv_wz = (ImageView) view.findViewById(R.id.iv_violate_regulations);
		iv_tx = (ImageView) view.findViewById(R.id.iv_notification);
		iv_qz = (ImageView) view.findViewById(R.id.iv_helper);

		iv_wz.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getActivity(), WeiZhangActivity.class));
			}
		});

		iv_tx.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getActivity(), TiXingActivity.class));
			}
		});
		iv_qz.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getActivity(), QiuZhuActivity.class));
			}
		});
		rl_pop_menu0 = (RelativeLayout) mPopView.findViewById(R.id.rl_item_00);
		rl_pop_menu1 = (RelativeLayout) mPopView.findViewById(R.id.rl_item_01);
		rl_pop_menu2 = (RelativeLayout) mPopView.findViewById(R.id.rl_item_02);
		rl_pop_menu3 = (RelativeLayout) mPopView.findViewById(R.id.rl_item_03);
		
		rl_pop_menu0.setOnClickListener(popOnItemClickListener);
		rl_pop_menu1.setOnClickListener(popOnItemClickListener);
		rl_pop_menu2.setOnClickListener(popOnItemClickListener);
		rl_pop_menu3.setOnClickListener(popOnItemClickListener);
		// 请求数据
		initData();

	}
	
	private OnClickListener popOnItemClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			switch(v.getId()){
			case R.id.rl_item_00:
				intent.setClass(getActivity(), AboutCjjActivity.class);
				break;
			case R.id.rl_item_01:
				intent.setClass(getActivity(), My_CarListActivity.class);
				break;
			case R.id.rl_item_02:
				intent.setClass(getActivity(), SettingInfoActivity.class);
				break;
			case R.id.rl_item_03:
				intent.setClass(getActivity(), SuggestActivity.class);
				break;
			}
			startActivity(intent);
			mPopupWindow.dismiss();
		}
	};

	public void onEventMainThread(Bundle bundle) {
		Log.e("mark", "onEventMainThread...");
		int type = bundle.getInt("type");
		if (type == 0) {
			if (mPopupWindow != null && mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
		}
	}

	// 初始化type类别
	private void initTabType() {
		requestInterface = new ProjectHttpRequestImpl(getActivity(), true);
		RequestParams params = new RequestParams();
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("token", Preferences.getSharedPreferences(getActivity(), "user_token", ""));
		requestInterface.requestSystemArticleClassWithDoneHandler("", params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				ArticlecClassBaseBean baseBean = dataInstance.getArticleClassBaseBean();
				if (baseBean != null) {
					if (baseBean.getCode() == 200) {
						ArticleType type = baseBean.getData();
						Fragment[] FRAGMENT_ARRAY = { MainActivityFragment.newInstance(), MainArticlesFragment.newInstance(type.getAcb_use()), MainServiceFragment.newInstance(type.getAcb_back()), MainNewCarFragment.newInstance(type.getAcb_new_car()) };
						FragmentPagerAdapter adapter = new MainPageAdapter(getChildFragmentManager(), FRAGMENT_ARRAY);
						pager.setAdapter(adapter);
						indicator.setViewPager(pager);
					} else {
						Toast.makeText(getActivity(), baseBean.getMsg(), Toast.LENGTH_SHORT).show();
					}
				} else {
					Log.e("mark", "ArticlecClassBaseBean is null!");
				}
			}
		});
	}

	private void initIndexWeather() {
		requestInterface = new ProjectHttpRequestImpl(getActivity(), true);
		RequestParams params = new RequestParams();
		String city = mApp.getNowCity();
		Log.d("mark", "city1:" + city);
		if (!TextUtils.isEmpty(city) && city.contains("市")) {
			int index = city.indexOf("市");
			if (city.length() == index + 1) {
				city = city.substring(0, index);
				Preferences.setEditor(mApp, "city", city);
			}
		} else {
			city = Preferences.getSharedPreferences(mApp, "city", "上海");
		}
		Log.d("mark", "city2:" + city);
		params.put("city", city);
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("token", Preferences.getSharedPreferences(getActivity(), "user_token", ""));
		requestInterface.requestIndexWeatherWithDoneHandler("", params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				WeatherBaseBean baseBean = dataInstance.getWeatherBaseBean();
				if (baseBean != null) {
					if (baseBean.getCode() == 200) {
						Weather weather = baseBean.getData();
						// 今天是周五: 限行 中雨转小雨 26-23℃
						String msg = weather.getWeather() + "  " + weather.getLow() + "-" + weather.getHigh() + "℃";
						// String week = Utils.getWeekOfDate(new
						// Date());
						String limit = weather.getLimit();
						if (TextUtils.isEmpty(limit)) {
							limit = "本地区不限号";
						}
						String tempMsg = "";
						if (limit.contains(",")) {
							tempMsg = getResources().getString(R.string.weather_msg, limit, msg);
						} else {
							tempMsg = limit + ";" + msg;
						}
						tv_weather_msg.setText(tempMsg);
						tv_notification_msg.setText("车家佳爱心提示:" + weather.getWash() + "洗车。");
					} else {
						Toast.makeText(getActivity(), baseBean.getMsg(), Toast.LENGTH_SHORT).show();
					}
				} else {
					Log.e("mark", "ArticlecClassBaseBean is null!");
				}
			}
		});
	}

	// private void initMessageCount(){
	// requestInterface = new ProjectHttpRequestImpl(getActivity(), false);
	// RequestParams params = new RequestParams();
	// params.put("client_id",ProjectHttpRequestInterface.client_id_key);
	// params.put("token", Preferences.getSharedPreferences(getActivity(),
	// "user_token", ""));
	// params.put("offset", "0");
	// params.put("num", "100");
	// requestInterface.requestMsgGetsDoneHandler("", params, new
	// AsyncHttpResponseHandler(){
	// @Override
	// public void onSuccess(String content) {
	// initMsgCount();
	// }
	// });
	// }

	private void initData() {
		initTabType();
		initIndexWeather();
		// initMessageCount();
	}

	@Override
	public void onResume() {
		super.onResume();
		CarInfo carInfo = dataInstance.getDefaultCarInfo();
		if (carInfo != null) {
			imageLoader.displayImage(carInfo.getBrand_icon(), iv_car_logo);
			tv_car_nums.setText(carInfo.getNative_plate());
		}
		initMsgCount();
	}

	private void initMsgCount() {
		int no_read_count = dataInstance.getNo_read_count();
		if (no_read_count != 0) {
			tv_notification_count.setText(String.valueOf(no_read_count));
			tv_notification_count.setVisibility(View.VISIBLE);
		} else {
			tv_notification_count.setText("0");
			tv_notification_count.setVisibility(View.GONE);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	private static final String[] CONTENT = new String[] { "活动", "用品", "后服务", "新车" };

	class MainPageAdapter extends FragmentPagerAdapter {
		private Fragment[] FRAGMENT_ARRAY;

		public MainPageAdapter(FragmentManager fm, Fragment[] FRAGMENT_ARRAY) {
			super(fm);
			this.FRAGMENT_ARRAY = FRAGMENT_ARRAY;
		}

		@Override
		public Fragment getItem(int position) {
			return FRAGMENT_ARRAY[position];
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return CONTENT[position % CONTENT.length].toUpperCase();
		}

		@Override
		public int getCount() {
			return CONTENT.length;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.header_right_button:
			showPopWindow();
			break;
		}
	}

	private PopupWindow mPopupWindow;
	private View mPopView;

	private void showPopWindow() {
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			mPopupWindow = new PopupWindow(mPopView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			mPopupWindow.setOutsideTouchable(true);
			mPopupWindow.showAsDropDown(mHeaderRightButton, 100, 10);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
		return false;
	}

}
